package cn.blnp.net.flowable.config;

import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.delegate.event.FlowableActivityEvent;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

/**
 * <h3>流程日志监听器配置</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/5/22 13:56
 */
@Slf4j
@Component
public class FlowableLoggingListener implements FlowableEventListener {
    @Override
    public void onEvent(FlowableEvent event) {
        switch (event.getType().name()) {
            case "TASK_CREATED":
                TaskEntity task = (TaskEntity) ((FlowableEngineEntityEvent)event).getEntity();
                log.info("任务创建 | ID:{} | 名称:{} | 处理人:{}",
                        task.getId(), task.getName(), task.getAssignee());
                break;
            case "PROCESS_STARTED":
                ExecutionEntity process = (ExecutionEntity) ((FlowableEngineEntityEvent)event).getEntity();
                log.info("流程启动 | 实例ID:{} | 定义ID:{}",
                        process.getId(), process.getProcessDefinitionId());
                break;
            case "ACTIVITY_STARTED":
                FlowableActivityEvent activityEvent = (FlowableActivityEvent) event;
                log.debug("节点进入 | 类型:{} | ID:{}",
                        activityEvent.getActivityType(), activityEvent.getActivityId());
                break;
        }
    }

    @Override
    public boolean isFailOnException() {
        // 防止监听器异常中断流程
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
